<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Cookie;
use think\Session;
use think\Image;
require_once APP_PATH . '/../extend/aliyun-oss/autoload.php'; //引入阿里云OSS SDK，注意替换路径
use OSS\Core\OssException;
use OSS\OssClient;
//require_once APP_PATH . '/../extend/PclZip/PclZip.php';
use PclZip\PclZip;
class Ds extends Controller
{   
    public function liveScoring()
    {
        if(request()->isAjax())
        {
            $scoringId = input('id');
            $scoringInfo = Db::connect("live_db_config")->table('wzbagent_live_scoring_config')->where('id',$scoringId)->find();
            return ['scoringInfo'=>$scoringInfo];
        }
        else
        {
            $this->assign([
                'scoring_id'=>input('id'),
            ]);
            return view();
        }

    }
    
    public function avatar()
    {
        header('content-type:image/png;');
        $id = input('id')?:session('uid','','admin');
        if(is_file('./uploads/avatar/admin_'.$id.'.png'))
            echo file_get_contents('./uploads/avatar/admin_'.$id.'.png');
        else
            echo file_get_contents('./uploads/avatar/default.png');
    }
    
    public function updateRank()
    {
        //?x-oss-process=image/auto-orient,1/quality,q_90/watermark,image_d2F0ZXJtYXJrLzc4MDAucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzAvYnJpZ2h0LDcvY29udHJhc3QsOA,g_se,x_10,y_10
        /*$list = Db::connect("live_db_config")->table('ims_wzbagent_votes')->where('live_id','in','7800')->select();

        foreach ($list as $k=>$v)
        {
            if($v['pic'] && !strstr($v['pic'],'x-oss-process=image'))
            {
                $data['pic'] = $v['pic'].'?x-oss-process=image/auto-orient,1/quality,q_90/watermark,image_d2F0ZXJtYXJrLzc4MDAucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzAvYnJpZ2h0LDcvY29udHJhc3QsOA,g_se,x_10,y_10';
            }
            if($v['pic1'] && !strstr($v['pic1'],'x-oss-process=image'))
            {
                $data['pic1'] = $v['pic1'].'?x-oss-process=image/auto-orient,1/quality,q_90/watermark,image_d2F0ZXJtYXJrLzc4MDAucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzAvYnJpZ2h0LDcvY29udHJhc3QsOA,g_se,x_10,y_10';
            }
            if($v['pic2'] && !strstr($v['pic2'],'x-oss-process=image'))
            {
                $data['pic2'] = $v['pic2'].'?x-oss-process=image/auto-orient,1/quality,q_90/watermark,image_d2F0ZXJtYXJrLzc4MDAucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzAvYnJpZ2h0LDcvY29udHJhc3QsOA,g_se,x_10,y_10';
            }
            if($v['pic3'] && !strstr($v['pic3'],'x-oss-process=image'))
            {
                $data['pic3'] = $v['pic3'].'?x-oss-process=image/auto-orient,1/quality,q_90/watermark,image_d2F0ZXJtYXJrLzc4MDAucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzAvYnJpZ2h0LDcvY29udHJhc3QsOA,g_se,x_10,y_10';
            }
            if($v['pic4'] && !strstr($v['pic4'],'x-oss-process=image'))
            {
                $data['pic4'] = $v['pic4'].'?x-oss-process=image/auto-orient,1/quality,q_90/watermark,image_d2F0ZXJtYXJrLzc4MDAucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzAvYnJpZ2h0LDcvY29udHJhc3QsOA,g_se,x_10,y_10';
            }
            if($data)
            {
                
                Db::connect("live_db_config")->table('ims_wzbagent_votes')->where('id',$v['id'])->update($data);
            }
            unset($data);
        }*/
        /*$list = Db::connect("live_db_config")->table('ims_wzbagent_giftlogs')->where('live_id','in','8031,8074')->where('status',1)->group('xuan_id')->select();

        foreach ($list as $k=>$v)
        {
            $data =  Db::connect("live_db_config")->table('ims_wzbagent_giftlogs')->field('SUM(amount) as amount , SUM(ticket) as tickes ')->where('xuan_id',$v['xuan_id'])->where('status',1)->find();
            $data['amount'] = $data['amount']/100;
            echo $v['xuan_id'];
            print_r($data);
            
            Db::connect("live_db_config")->table('ims_wzbagent_votes')->where('id',$v['xuan_id'])->update($data);
        }*/
        
        // $list = Db::connect("live_db_config")->table('ims_wzbagent_lives')->where('depart_id',0)->select();

        // foreach ($list as $k=>$v)
        // {
        //     $data =  Db::connect("live_db_config")->table('ims_wzbagent_managers')->where('id',$v['admin_id'])->find();
        //     Db::connect("live_db_config")->table('ims_wzbagent_lives')->where('id',$v['id'])->update(['depart_id'=>$data['depart_id'] ]);
        // }
        // if(input('id'))
        // {
        //     if(input('month_company_rank'))
        //         db('admin')->where('id',input('id'))->update(['month_depart_rank'=>input('month_depart_rank'),'month_company_rank'=>input('month_company_rank'),'month_performance'=>input('month_performance')]);
        //     else
        //         db('admin')->where('id',input('id'))->update(['month_depart_rank'=>'','month_company_rank'=>'','month_performance'=>'']);
        // }
    }
    
    public function index1()
    {
        /*是否有到期客户*/
        $client = db('client')->where('status','in','1,3')->where('end_time','<',time())->select();
        if($client){
            foreach ($client as $k=>$v){
                $save = db('client')->where('id',$v['id'])->update(['xaid'=>0,'status'=>0,'baoA_time'=>0,'baoA_aid'=>0,'end_time'=>0]);
                if($save !== false){
                    echo "客户ID:".$v['id']."已转移到客户池中\n";die;
                }else{
                    echo "客户ID:".$v['id']."转移失败\n";die;
                }
            }
        }else{
            echo "暂无需要转移到客户池的客户\n";die;
        }
        die;
    }


    public function upload()
    {
        $file = request()->file('file');
        $folder = input()['folder'];
        $folder = $folder?$folder:'worksword';
        if($file)
        {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.$folder);
            if($info)
            {
                $filename = '/uploads/'.$folder.'/'.str_replace(DS, '/', $info->getSaveName() );
                $previewUrl = 'http://'. $_SERVER['HTTP_HOST'].$filename;
                return [
                    'status' => 1,
                    'filename' => $filename,
                    'previewUrl' => $previewUrl,
                    'msg' => '上传成功'
                ];
            }
            else
            {
                return [
                    'status' => -1,
                    'filename' => '',
                    'msg' => '上传失败，'.$file->getError()
                ];
                
            }
        }


    }
    
    public function getStockById()
    {
        $id = input('id');
        if($id)
        {
            $stock = db('goods')->where('id',$id)->value('stock');
            return ['stock'=>$stock];
        }
    }
    public function tokeninit()
    {
        $list = Db::connect("live_db_config")->table('ims_wzbagent_lives')->select();
        foreach ($list as $k=>$v)
        {
            Db::connect("live_db_config")->table('ims_wzbagent_lives')->where('id',$v['id'])->update(['token'=>substr(md5($v['id']),8,16)]);
        }
    }
    
    
    public function autoUpdate1()
    {
        $arr2 = db('client')->field('phone,id')->where("phone!='' AND phone NOT LIKE '%[%' ")->select();
        foreach ($arr2 as $k => $v) 
        {
            $arr2[$k]['phone'] = json_encode([$v['phone'] ]);
            db('client')->update($arr2[$k]);
        }
    }
    public function autoUpdate()
    {
        $list = Db::connect("live_db_config")->table('ims_wzbagent_votes')->where('live_id','6149')->select();
        foreach ($list as $k=>$v)
        {
            Db::connect("live_db_config")->table('ims_wzbagent_votes')->where('live_id','6149')->where('id',$v['id'])->update(['video'=>"http://img.htzhibo.com/images/votes_video_new/6146/".($v['sort']+800).".mp4"]);
        }
        
        if(db('admin')->where('status',1)->where('group_id',2)->cache(true)->where('department_id',0)->find())
        {
            $teamList = db('admin')->where('status',1)->where('group_id',5)->select();
            foreach ($teamList as $k=>$v)
            {
                if($v['id'] == 17)
                    $departmentId = 1;
                else if($v['id'] == 12)
                    $departmentId = 2;
                else if($v['id'] == 31)
                    $departmentId = 3;
                else if($v['id'] == 27)
                    $departmentId = 4;
                db('admin')->where('id','IN',$v['group_members'].','.$v['id'])->update(['department_id'=>$departmentId]);
            }
        }
        
        
        $adminId = session('uid','','admin');

        $workRemindCheck = db('work')->field('id')->where('aid',$adminId)->where('pizhu_text|pizhu','<>','')->where('remind_status',0)->order('id desc')->find();
        if($workRemindCheck)
        {
            db('work')->where('id',$workRemindCheck['id'])->update(['remind_status'=>1]);
        }
        
        $khcCount = db('client')->where('status',0)->cache(true,3600,'file')->count();
        if(session('group_members','','admin')[1]){
            $groupMembers = implode(',',session('group_members','','admin'));
            $xuqiCount = db('xuqi')->alias('x')->join('client c','x.client_id=c.id')->where('c.xaid','IN',$groupMembers)->where('x.aid','IN',$groupMembers)->where('x.review_id IS NULL ')->count();
            $addApplyCount = db('client_apply')->where('add_admin_id','IN',$groupMembers)->where('reply_admin_id IS NULL ')->count();
            $applyCount = db('apply')->where('admin_id','IN',$groupMembers)->where('reply_admin_id IS NULL ')->count();
            $contractCount = db('client')->where('xaid','IN',$groupMembers)->where('chat_check_status',-1)->where('status',4)->count();
        }
        
        if(session('group_id','','admin') == 7 || session('group_id','','admin') == 1)
        {
            $backOrderCount = db('goods_orders')->where('status',0)->where('type',2)->count();
        }
        
        if(in_array(session('group_id','','admin'),[1,2,5]))
        {
            $qiandanList = db('client')->alias('c')->field('c.id,c.activity,a.name')->join('admin a','a.id=c.xaid')->where('c.qiandan_time','>',time()-86400 )->where('c.status',4)->where('c.chat_check_status','>',-1)->select();
            foreach ($qiandanList as $k=>$v)
            {
                if(Cookie::get('remind_'.$v['id']) == 1)
                    unset($qiandanList[$k]);
            }
            $qiandanCount = count($qiandanList);
            
            $sqRemindCount = db('datatable_live_process')->where('admin_id',$adminId)->where('step = 1 OR (step = 3 AND activity_end_time < '.time().') ')->count();
            
        }
        
        if(in_array(session('uid','','admin'),[1,12]))
        {
            $zxRemindCount = db('datatable_live_process')->where('step','IN','0,2')->count();
            $jsRemindCount = db('datatable_live_process')->where('step','IN','4')->count();
        }
        
        echo json_encode(['workremind' => $workRemindCheck,'khcCount'=>$khcCount,'xuqiCount'=>$xuqiCount,'applyCount'=>$applyCount,'addApplyCount'=>$addApplyCount,'backOrderCount'=>$backOrderCount,'contractCount'=>$contractCount ,'qiandanCount'=>$qiandanCount,'sqRemindCount'=>$sqRemindCount,'zxRemindCount'=>$zxRemindCount,'jsRemindCount'=>$jsRemindCount ] ,JSON_UNESCAPED_SLASHES);
        //return ['workremind' => $workRemindCheck];
    }
    

    
    public function aotoVoteSetting()
    {
        $navList = Db::connect("live_db_config")
                    ->table('ims_wzbagent_navs')
                    ->alias('n')
                    ->field('n.*')
                    ->join('ims_wzbagent_lives l','n.live_id = l.id')
                    ->where('l.admin_id', 308)
                    ->where('n.type', 8)
                    ->where('n.isshow', 1)
                    ->select();
        foreach($navList as $k=>$v)
        {
            $settingData = ['nid'=>$v['id'],'rid'=>$v['rid'],'uniacid'=>$v['uniacid'],'total_can_votes'=>3,'day_can_votes'=>3,'same_can_votes'=>3,'start_at'=>1642435200,'end_at'=>1645372800,'created_at'=>1642486366,'updated_at'=>1642486366,'live_id'=>$v['live_id'],'daily'=>500];
            $check = Db::connect("live_db_config")->table('ims_wzbagent_vote_setting')->where('nid',$v['id'])->find();
            if($check)
            {
                Db::connect("live_db_config")->table('ims_wzbagent_vote_setting')->where('nid',$v['id'])->update($settingData);
            }
            else
            {
                Db::connect("live_db_config")->table('ims_wzbagent_vote_setting')->insertGetId($settingData);
            }
        }
        
    }
    
    public function test0715()
    {
        $list = Db::connect("live_db_config")->table('ims_wzbagent_giftlogs')->where('pay_uniacid', 30)->where('status', 1)->where('dateline','>', 1656305893)->order('id ASC')->select();
        foreach ($list as $k=>$v)
        {
            $data = [
                        'uid'=>$v['uid'],
                        'openid'=>'',
                        'wxapp_id'=>$v['wxapp_id'],
                        'pay_uniacid'=>$v['pay_uniacid'],
                        'giftlog_id'=>$v['id'],
                        'live_id'=>$v['live_id'],
                        'order_amount'=>$v['amount'],
                        'sharing_amount'=>intval($v['amount']*0.3),
                        'out_order_no'=>$v['out_trade_no'],
                        'transaction_id'=>$v['transaction_id'],
                        'status'=>0,
                        'creat_time'=>time(),
                        'is_small'=>1
                    ];
             Db::connect("live_db_config")->table('ims_wzbagent_profit_sharing')->insertGetId($data);
        }
        exit();
        
        
        $list = Db::connect("live_db_config")->table('ims_wzbagent_vote_setting')->whereTime('start_at','between',[strtotime('2022-05-01'),strtotime('2022-06-30')])->select();
        
        $money = $money1 = $count1 = $count = 0;
        foreach ($list as $k=>$v)
        {
            if($v['live_id'])
            {
                $v['money'] = Db::connect("live_db_config")->table('ims_wzbagent_giftlogs')->where('live_id',$v['live_id'])->where('status',1)->value('sum(amount)');
                $v['money1'] = Db::connect("live_db_config")->table('ims_wzbagent_giftlogs')->where('dateline','>=',$v['end_at'])->where('live_id',$v['live_id'])->where('status',1)->value('sum(amount)');
                $money+=$v['money'];
                $money1+=$v['money1'];
                if($v['money'])
                    $count ++;
                if($v['money1'])
                    $count1 ++;
            }
        }
        var_dump($count);var_dump($count1);
        var_dump($money);var_dump($money1);
    }
    
    public function batchUploadVote()
    {
        $file = request()->file('block');
        if($file)
        {
            $total = input('total');
            $index = input('index');
            $sort = input('sort');
            $postfix = input('postfix');
            $info = $file->move( '../uploads/votetemp');
            if($info)
            {
                
                $result = '../uploads/votetemp/'.$info->getSaveName();
                session($index,$result,'task');
                if($index == $total)
                {
                    $list = session('','','task');
                    $fp = fopen('./uploads/votetemp/'.session('task_name'),"ab");
                    foreach($list as $value)
                    {  
                        if(!empty($value))
                        {  
                            $handle = fopen($value,"rb");  
                            fwrite($fp,fread($handle,filesize($value)));  
                            fclose($handle);  
                            unset($handle);  
                        }  
                    }  
                    fclose($fp);
                    $zipName = $_SERVER['DOCUMENT_ROOT'].iconv('UTF-8', 'GB2312', '/uploads/votetemp/'.session('task_name'));
                    //$toDir = $_SERVER['DOCUMENT_ROOT'].'/uploads/votetemp/'.session('task_name');
                    $toDir = substr($zipName,0,-4);
                    
                    $zip = new \PclZip\PclZip();
                    $zip->PclZip(iconv('utf-8', 'gb2312', $zipName));
                    // if (($list = $zip->listContent()) == 0) 
                    // {
                    //     die("Error : " . $zip->errorInfo(true));
                    // }
                    $unzip = $zip->extract(PCLZIP_OPT_PATH, $toDir);
                    if($unzip == 0)
                    {
                        return ['code'=>-1,$zip->errorInfo(true)];
                    }
                    else
                    {
                        $teamList = getDirContent($toDir);
                        foreach ($teamList as $k=>$v)
                        {

                            
                            if(strstr($v,'.'))
                            {
                                //$voteList = getDirContent($toDir);
                                $data['task_name'] = session('task_name');
                                $data['live_id'] = session('live_id' );
                                $data['uniacid'] = session('uniacid' );
                                $data['rid'] = session('rid' );
                                $data['nav_id'] = session('navId' );
                                $data['name'] = explode('.',$v)[0];
                                $data['photos'] = json_encode(['/uploads/votetemp/'.substr(session('task_name'),0,-4).'/'.$v]);
                                $data['folder'] = $_SERVER['DOCUMENT_ROOT'];
                                $data['add_time'] = time();
                                db('batch_votes')->insert($data);
                                unset($data);
                                
                                /*foreach ($voteList as $k=>$v)
                                {}*/
                            }
                            else
                            {
                                $voteList = getDirContent($toDir.'/'.$v);
                                foreach ($voteList as $kk=>$vv)
                                {
                                    if($sort)
                                        $data['sort'] = $sort+$kk;
                                        $data['team_name'] = $v;
                                        $data['task_name'] = session('task_name');
                                        $data['live_id'] = session('live_id' );
                                        $data['uniacid'] = session('uniacid' );
                                        $data['rid'] = session('rid' );
                                        $data['nav_id'] = session('navId' );
                                        //$data['name'] = explode('.',$vv)[0];
                                        $name = explode('.',$vv)[0];
                                        //$name1 = explode('《',$name)[0];
                                        //$name2 = explode('《',$name)[1];
                                        //$name2 = explode('》',$name2)[0];
                                        $data['name'] = $v?"{$name}{$v}":"{$name}";
                                        
                                        $photoList = getDirContent($toDir.'/'.$v.'/'.$name.'');
                                        foreach ($photoList as  $kkk=>$vvv)
                                        {
                                            if($kkk < 5 && (stripos($vvv,'jpg') || stripos($vvv,'jpeg') || stripos($vvv,'png') || stripos($vvv,'bmp')))
                                                $data['photos'][] = '/uploads/votetemp/'.substr(session('task_name'),0,-4).'/'.$v.'/'.$name.'/'.$vvv;
                                        }
                                        $data['photos'] = json_encode($data['photos'],JSON_UNESCAPED_UNICODE);
                                        //$data['photos'] = json_encode(['/uploads/votetemp/'.substr(session('task_name'),0,-4).'/'.$v.'/'.$vv],JSON_UNESCAPED_UNICODE);
                                        
                                        $data['folder'] = $_SERVER['DOCUMENT_ROOT'];
                                        $data['add_time'] = time();
                                        
                                        db('batch_votes')->insert($data);
                                        unset($data);
                                    }
                                }
                            }
                            

                        /*
                        */
                        return ['code'=>1,'task_name'=>session('task_name')];
                    }
                   
                    /*
                    $zip = new \ZipArchive();
                    // $unzipStatus = shell_exec("unzip -O gbk -d {$toDir} {$zipName}");
                    // echo "unzip -O gbk -d {$toDir} {$zipName}".$unzipStatus;exit;
                    if ($zip->open($zipName) == true) 
                    {
                        /*$docnum = $zip->numFiles;
                        @mkdir(iconv ( 'UTF-8', 'GBK', $toDir), 0777, true);
                        for($i = 0; $i < $docnum; $i++) 
                        {
                            $statInfo = $zip->statIndex($i);
                            if($statInfo['crc'] == 0) {
                                mkdir(iconv ( 'UTF-8', 'GBK', $toDir.'/'.$statInfo['name']), 0777, true);
                            } else {
                                if(copy('zip://'.$zipName.'#'.$statInfo['name'], iconv ( 'UTF-8', 'GBK', $toDir.'/'.$statInfo['name'])) == false){
                                    echo 'faild to copy';
                                }
                            }
                        }
                        $zip->extractTo($toDir);
                        $zip->close();
                        $voteList = getDirContent($toDir);
                        if($voteList )
                        {
                            @unlink($zipName);
                            print_r($voteList);
                            
                        }
                    } 
                    else 
                    {
                        return ['code'=>0,'msg'=>'压缩包错误，请重试，必须用ZIP'];
                    }*/
                }
                return ['code'=>0,'data'=>$result];
            }
            else
            {
                return ['code'=>-1,'msg'=>$file->getError()];
            }
            //$res = self::AliuploadFile('test', $file);
            //print_r($res);
        }
        else
        {
            session(null,'task');
            session('task_name', rand(1,900).time().'.zip' );
            $liveId = input('live_id');
            $navId = input('nav_id');
            $rid = input('rid');
            $uniacid = input('uniacid');
            session('live_id',$liveId );
            session('uniacid',$uniacid );
            session('rid',$rid );
            session('navId',$navId );
            $task = db('batch_votes')->where('status',0)->where('nav_id',$navId)->select();
            if($task)
            {
                header("Location:batchUploadVoteStep2?task_name=".$task[0]['task_name']);
            }
            $this->assign([
                'task'=>$task
            ]);
            return view();
        }
    }
    
    public function batchUploadVoteStep2()
    {
        $taskName = input('task_name');
        if(!$taskName)
            return '无选手';
        $list = db('batch_votes')->where('task_name',$taskName)->select();
        $this->assign([
            'list'=>$list
        ]);
        return view();
    }
    
    public function batchUploadVoteStep3()
    {
        $taskName = input('task_name');
        if(!$taskName)
            return ['msg'=>'无选手','code'=>0];
        $list = db('batch_votes')->where('task_name',$taskName)->where('status',0)->select();
        
        foreach ($list as $k=>$v)
        {
            $teamTable = Db::connect("live_db_config")->table('ims_wzbagent_vote_team');
            $voteTable = Db::connect("live_db_config")->table('ims_wzbagent_votes');
            if($v['team_name'])
            {
                // $teamId = Db::connect("live_db_config")->table('ims_wzbagent_vote_team')->where('team_name','like',"%{$v['team_name']}%")->where('navs_id',$v['nav_id'])->value('id');
                // if(!$teamId && $v['team_name'])
                // {
                //     $teamData = ['rid'=>$v['rid'],'navs_id'=>$v['nav_id'],'uniacid'=>$v['uniacid'],'live_id'=>$v['live_id'],'team_name'=>$v['team_name'],'sort'=>0 ];
                //     $teamId = Db::connect("live_db_config")->table('ims_wzbagent_vote_team')->insertGetId($teamData);
                // }
                $v['photos'] = json_decode($v['photos'],true);
                $voteData = ['rid'=>$v['rid'],'navs_id'=>$v['nav_id'],'uniacid'=>$v['uniacid'],'live_id'=>$v['live_id'],'name'=>$v['name'],'team_id'=>$teamId ];
                $voteId = Db::connect("live_db_config")->table('ims_wzbagent_votes')->insertGetId($voteData);
                if($v['sort'])
                    $voteData2['sort'] = $v['sort'];
                else
                    $voteData2 = ['sort'=>$voteId];
                foreach ($v['photos'] as $kk => $vv)
                {
                    if($kk < 5)
                    {
                        $file = $v['folder'].$vv;
                        if(stripos($file,'DS_Store') === false && stripos($file,'Thumbs') === false  && stripos($file,'/.') === false )
                            $res = self::AliuploadFile('images/0/batch/'.date('Y').'/'.date('m').'/'.date('d').'/'.$voteId, $file ,$kk);
                        if($res['code'] == 200)
                        {
                            $keyName = $kk == 0?'pic':'pic'.$kk;
                            $voteData2[$keyName] = str_replace('haitun-live.oss-cn-beijing.aliyuncs.com','img.htzhibo.com',$res['data']);
                        }
                    }

                }
                Db::connect("live_db_config")->table('ims_wzbagent_votes')->where('id',$voteId)->update($voteData2);
                $voteData2 = [];
                db('batch_votes')->where('id',$v['id'])->update(['status'=>1]);
            }
        }
        return ['code'=>1];
    }
    
    public static function AliuploadFile($module, $file ,$key)
    {
        @$resResult = Image::open($file);
        try {
            //获取OSS参数值
            $KeyId = config('alioss.AccessKeyID');
            $KeySecret = config('alioss.AccessKeySecret');
            $EndPoint = config('alioss.EndPoint');
            $Bucket = config('alioss.Bucket');
            //实例化
            $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
            //sha1加密 生成文件名 连接后缀
            $fileName = $module .'_'.$key. '.'.$resResult->type();// . explode('.',$file)[ count(explode('.',$file))-1 ] ; //$resResult->type();
            //执行阿里云上传
            $result = $ossClient->uploadFile($Bucket, $fileName, $file);
            //图片地址:$result['info']['url']
            $arr = ['code' => 200, 'msg' => '上传成功', 'data' => $result['info']['url']];
        } catch (OssException $e) {
            $arr = ['code' => 0, 'msg' => $e->getMessage(), 'data' => ''];
        }
        return $arr;
    }
    
    public function getHxcData()
    {
        $id = input()['id'];//input()['id']?:db('other_xbjb')->order('vote_id DESC')->value('vote_id') - 100;
        $data = request_post("https://zb.hbtcxn.cn/api/page/home",'{"page":1,"id":"'.$id.'","search":""}' ,'json');
        $data = json_decode($data,true)['data'];
        echo '正在获取活动ID '.$id.$data['activity_data']['name'];
        print_r($data);
        if($data['id'])
        {
            $data['activity_data']['createtime'] = date('Y-m-d H:i',$data['activity_data']['createtime']);
            if(db('other_hxc')->where('id',$id)->find() )
                $sqlStatus = db('other_hxc')->where('id',$id)->update($data['activity_data'])?1:1;
            else
                $sqlStatus = db('other_hxc')->insert($data['activity_data']);
            
            if($sqlStatus)
            {
                $id ++ ;
                echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getHxcData?id={$id}'\",50);</script>";
            }
        }
        else
        {
            $id ++ ;
            
            echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getHxcData?id={$id}'\",50);</script>".'已更新完毕/或出错了';
        }
        
    }

    public function getXbjbData()
    {
        // $page = $_GET['page'];
        // $data = db('other_xbjb')->where()->limit(($page+1)*1 ,1)->select();
        // foreach ($data as $key=>$value)
        // {
        //     //操作
        // }
        // $page++;
        // echo "<script>window.setTimeout(\"window.location='这个控制器的url?page={$page}'\",500);</script>";
        
        // https://api.xiangbojiubo.com/v3/api/vote/detail?vote_id=37029
        $id = input()['id']?:db('other_xbjb')->order('vote_id DESC')->value('vote_id') - 100;
        $data = request_post("http://www.hkinly.cn/v3/api/vote/detail?vote_id={$id}&locale=zh-CN");
        $data = json_decode($data,true);
        echo '正在获取活动ID '.$id.$data['data']['name'].$data['data']['vote_count'];
        if($data['xcode'] == '200')
        {
            //['vote_id'=>$data['data']['vote_id'],'name'=>$data['data']['name'],'start_time'=>$data['data']['start_time'],'end_time'=>$data['data']['end_time'] ]
            if(db('other_xbjb')->where('vote_id',$id)->find() )
                $sqlStatus = db('other_xbjb')->where('vote_id',$id)->update($data['data'])?1:1;
            else
                $sqlStatus = db('other_xbjb')->insert($data['data']);
            
            if($sqlStatus)
            {
                $id ++ ;
                echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getXbjbData?id={$id}'\",50);</script>";
            }
        }
        else{
                $id ++ ;
                echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getXbjbData?id={$id}'\",50);</script>";
                echo '已更新完毕/或出错了';
            }
    }

    public function getXbjbCategoryData()
    {
        $id = input()['id']?:db('other_xbjb_category')->order('category_id DESC')->value('category_id') - 100;
        $data = request_post("https://api.xiangbojiubo.com/v2/api/home/category/video?name=&category_id={$id}&page=1&size=20");
        $data = json_decode($data,true);
        echo '正在获取专题ID '.$id.$data['data']['name'];
        print_r($data);
        if($data['xcode'] == '200')
        {
            foreach($data['data'] as $k=>$v)
            {
                if($v['name'])
                {
                    if(db('other_xbjb_category')->where('id',$v['id'])->find() )
                        $sqlStatus = db('other_xbjb_category')->where('id',$v['id'])->update($v)?1:1;
                    else
                        $sqlStatus = db('other_xbjb_category')->insert($v);
                        
                    if($v['token'])
                    {
                        $data = request_post("https://api.xiangbojiubo.com/v3/api/video/detail?token=".$v['token']);
                        $data = json_decode($data,true);
                        if($data['data']['tpl_content']['wechat']['name'])
                        {
                            db('other_xbjb_category')->where('id',$v['id'])->update(['wechat_name'=>$data['data']['tpl_content']['wechat']['name'] ]);
                        }
                        
                    }
                }

            }
        
            $id ++ ;
            echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getXbjbCategoryData?id={$id}'\",200);</script>";
        }
        else
            echo '已更新完毕/或出错了';
    }
    
    public function getSsxgData()
    {
        $id = input()['id']?:db('other_ssxg')->order('id DESC')->value('id') - 100;
        $data = request_post("http://live.szybcm.cn/service/vote-info?vote_id={$id}");
        $data = json_decode($data,true);
        echo '正在获取活动ID '.$id.$data['data']['name'];
        if($data['code'] == '200')
        {
            $data['data']['ds_list'] = $data['data']['content']['ds_list'];
            if(db('other_ssxg')->where('id',$id)->find() )
                $sqlStatus = db('other_ssxg')->where('id',$id)->update($data['data'])?1:1;
            else
                $sqlStatus = db('other_ssxg')->insert($data['data']);
            
            if($sqlStatus)
            {
                $id ++ ;
                echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getSsxgData?id={$id}'\",200);</script>";
            }
        }
        else
            echo '已更新完毕/或出错了';
    }
    
    public function getSsxgCategoryData()
    {
        $id = input()['id']?:40;
        $data = request_post("https://live.szybcm.cn/service/group/?vgroup_id={$id}");
        
        $data = json_decode($data,true);
        echo '正在获取专题ID '.$id.$data['data']['name'];
        if($data['code'] == '200')
        {
            foreach($data['data'] as $k=>$v)
            {
                $v['id'] = $data['sql'][$k];
                $v['category_id'] = $id;
                if(db('other_ssxg_category')->where('id',$v['id'] )->find() )
                    $sqlStatus = db('other_ssxg_category')->where('id',$v['id'] )->update($v)?1:1;
                else
                    $sqlStatus = db('other_ssxg_category')->insert($v);
            }
        
            $id ++ ;
            echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getSsxgCategoryData?id={$id}'\",200);</script>";
        }
        else
            echo '已更新完毕/或出错了';
    }
    public function getJczbData()
    {
        $id = input()['id']?:db('other_jczb')->order('camera_id DESC')->value('camera_id') - 150;
        $data = request_post("https://mini.jingchangkan.cn/live/mini/getCameraInfo?token=&duid=1&camera_id={$id}");
        $data = json_decode($data,true);
        //print_r($data);
        echo '正在获取活动ID '.$id.$data['data']['title'];
        if($data['code'] == '200')
        {
            $vData = request_post("https://mini.jingchangkan.cn/live/mini/getVoteBaseInfo?token=&duid=1&camera_id={$id}&group_id=0");
            $vData = json_decode($vData,true);
            $data['data']['total_person'] = $vData['data']['total_person'];
            $data['data']['total_voting'] = $vData['data']['total_voting'];
            if(db('other_jczb')->where('camera_id',$id)->find() )
                $sqlStatus = db('other_jczb')->where('camera_id',$id)->update($data['data'])?1:1;
            else
                $sqlStatus = db('other_jczb')->insert($data['data']);
            
            if($sqlStatus)
            {
                $id ++ ;
                echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getJczbData?id={$id}'\",200);</script>";
            }
        }
        else if($data['code'] == 104)
        {
            $id ++ ;
            echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getJczbData?id={$id}'\",200);</script>";
        }  
        else
            echo '已更新完毕/或出错了';
    }
    
    public function getJzzbData()
    {
        $id = input()['id']?:db('other_jzzb')->order('voteid DESC')->value('voteid') - 150;
        $data = request_post("https://toupiao-1304312940.file.myqcloud.com/vote/vote_{$id}.json?uptime=0");
        if(strpos($data,'NoSuchKey'))
        {
            $id ++ ;
            echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getJzzbData?id={$id}'\",200);</script>";
            exit();
        }
        $data = json_decode($data,true);
        print_r($data);
        echo '正在获取活动ID '.$id;
        if($data['errno'] == '0' && $data['data']['title'])
        {
            $data['data']['title'] = $data['data']['title2'];
            if(db('other_jzzb')->where('voteid',$id)->find() )
                $sqlStatus = db('other_jzzb')->where('voteid',$id)->update($data['data'])?1:1;
            else
                $sqlStatus = db('other_jzzb')->insert($data['data']);
            
            if($sqlStatus)
            {
                $id ++ ;
                echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getJzzbData?id={$id}'\",200);</script>";
            }
        }
        else if($data['errno'] == -1)
        {
            $id ++ ;
            echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getJzzbData?id={$id}'\",200);</script>";
        }
        else
            echo '已更新完毕/或出错了';
    }
    
    
    public function getXbjbData11()
    {
        $id = input()['id'];
        $data = request_post("http://www.hkinly.cn/v3/api/vote/detail?vote_id={$id}&locale=zh-CN");
        $data = json_decode($data,true);
        print_r($data);
        if($data['xcode'] == '200')
        {
            //['vote_id'=>$data['data']['vote_id'],'name'=>$data['data']['name'],'start_time'=>$data['data']['start_time'],'end_time'=>$data['data']['end_time'] ]
            $sqlStatus = db('xbjb')->insert($data['data']);
            if($sqlStatus)
            {
                $id ++ ;
                echo "<script>window.setTimeout(\"window.location='/admin.php/ds/getXbjbData?id={$id}'\",200);</script>";
            }
        }
        
    }

    public function test()
    {
        $arr = db('client')->where('end_time','<',time())->where('status','IN','1,3')->select();
        
        foreach ($arr as $k => $v) 
        {
            db('cancel_log')->insert(['uid'=>$v['xaid'],'client_id'=>$v['id'],'add_time'=>time()]);
            db('client')->where('id',$v['id'])->update(['xaid'=>0,'status'=>0,'baoA_time'=>0,'baoA_aid'=>0,'end_time'=>0]);
            if($v['status'] == 3)
            {
                db('client')->where('id',$v['id'])->update(['group_admin_id'=>$v['xaid'],'group_time'=>time()]);
            }
        }
        
        $arr1 = db('client')->where('union_id',0)->where('status','IN','1,3')->cache(60)->select();
        foreach ($arr1 as $k => $v) 
        {
            db('client')->where('id',$v['id'])->update(['union_id'=>$v['id']] );
        }
        $arr2 = db('client')->where('union_id = id')->where('status','IN','1,3')->cache(60)->select();
        foreach ($arr2 as $k => $v) 
        {
            $union_id = $union_id1 = $union_id2 = '';
            if($v['phone'])
                $union_id1 = db('client')->where('phone',$v['phone'])->whereOr('wx','LIKE','%'.$v['phone'].'%')->order('id asc')->value('union_id');
            if($v['wx'])
                $union_id2 = db('client')->where('wx',$v['wx'])->whereOr('phone','LIKE','%'.$v['wx'].'%')->order('id asc')->value('union_id');
            if($union_id2)
                $union_id = $union_id2;
            if($union_id1)
                $union_id = $union_id1;
            if($union_id)
                db('client')->where('id',$v['id'])->update(['union_id'=>$union_id] );
        }
        echo 'success';
    }











}
